package com.zjs.jsp.fdservice.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjs.jsp.domain.jsp.AddOrder;
import com.zjs.jsp.domain.jsp.Jsp_Order;
import com.zjs.jsp.domain.jsp.Jsp_Task;
import com.zjs.jsp.fdservice.Interface.SendJspTaskInterface;
import com.zjs.jsp.fdservice.service.mongodb.ExceptionOrderExpand;
import com.zjs.jsp.fdservice.service.mongodb.JspTaskExpand;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * 发送任务包到下游MQ
 *
 * @author 李文
 * @create 2017-09-02 10:29
 **/
public class SendJspTask implements SendJspTaskInterface
{

    private static final ObjectMapper jsonMapper = new ObjectMapper();

    @Autowired
    private ExceptionOrderExpand exoExpand;

    @Autowired
    private Producer producer;

    @Autowired
    private JspTaskExpand jspTaskExpand;


    /**
     * 发送数据到MQ
     *
     * @param strBody  原始数据字符串
     * @param jspOrder 转换后的 实体类
     * @param addOrder 追加订单下发数据实体类
     * @param task     任务包首次下发数据实体类
     * @return
     */
    @Override
    public Boolean sendMqData(String strBody, Jsp_Order jspOrder, AddOrder addOrder, Jsp_Task task) {
        String jspTask = null;
        String as = null;
        try {
            if (!StringUtils.isEmpty(task)) {
                jspTask = jsonMapper.writeValueAsString(task);
            } else {
                as = jsonMapper.writeValueAsString(addOrder);
            }
        } catch (JsonProcessingException e) {
            exoExpand.saveEx(jspOrder, e, "下发数据转换JSon异常  数据： " + strBody, 4, "下发数据转换JSon 异常 " + e.getMessage());
            return false;
        }

        SendResult result;
        try {
            if (!StringUtils.isEmpty(task)) {
                result = producer.sendMQ(jspTask, as, jspOrder.getPoc());
            } else {
                task = new Jsp_Task();
                task.setId(addOrder.getTid());
                result = producer.sendMQ(jspTask, as, jspOrder.getPoc());
            }
        } catch (Exception e) {
            exoExpand.saveEx(jspOrder, e, "下发 发送MQ 异常  数据是： " + strBody, 5, "下发 发送MQ 异常 " + e.getMessage());
            return false;
        }
        // 发送MQ 失败
        if (result == null) {
            return false;
        }


        // 更新任务包为 已下发
        try {
            if (!StringUtils.isEmpty(task)) {
                task.setUd(new Date());
                jspTaskExpand.update(task.getTk(), task.getUd());
            }
        } catch (Exception e) {
            // 下发成功 修改数据库状态 异常
            exoExpand.saveEx(jspOrder, e, "下发成功修改数据库状态 数据： " + strBody, 6, "下发成功 修改数据库状态 " + e.getMessage());
            return false;
        }
        return true;
    }
}
